# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
import random

from qihu_search.user_agents import AGENTS


class RandomUserAgent(object):
    def process_request(self, request, spider):
        if spider.name == 'toutiao_search':
            useragent = random.choice(AGENTS)
            #print(useragent)
            request.headers["User-Agent"] = useragent

# class RandomUserAgent(object):
#     """Randomly rotate user agents based on a list of predefined ones"""
#
#     def __init__(self, agents):
#         self.agents = agents
#
#     @classmethod
#     def from_crawler(cls, crawler):
#         return cls(crawler.settings.getlist('USER_AGENTS'))
#
#     def process_request(self, request, spider):
#         request.headers.setdefault('User-Agent', random.choice(self.agents))

import os
import random
import socket
import re
class ProxyMiddleware(object):
    def __init__(self):
        self.proxy_pool = [{'ip_port': '123.160.246.41:3130'}]
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('baidu.com', 80))
            if s.getsockname()[0] in ['123.160.246.41', '218.28.2.162']:
                self.proxy_pool = [{'ip_port': '127.0.0.1:3130'}]
        except Exception as e:
            print(e)
            rep = '^((192\.168|172\.([1][6-9]|[2]\d|3[01]))(\.([2][0-4]\d|[2][5][0-4]|[01]?\d?\d)){2}|10(\.([2][0-4]\d|[2][5][0-4]|[01]?\d?\d)){3})$'
            output = os.popen('/sbin/ifconfig|grep "inet "|grep -v "127.0.0.1"|xargs').read()
            tmp_ip_info = re.split(' |:', output)
            for i in tmp_ip_info:
                rep_ip = re.search(rep, i)
                if rep_ip and rep_ip.string in ['172.16.13.10', '172.16.13.11']:
                    self.proxy_pool = [{'ip_port': '127.0.0.1:3130'}]
        finally:
            s.close()


    # overwrite process request
    def process_request(self, request, spider):
        # Set the location of the proxy
        thisproxy = random.choice(self.proxy_pool)
        request.meta['proxy'] = "http://" + thisproxy["ip_port"]


